﻿using System;
using System.ComponentModel;
using System.Reflection;

namespace DotnetUtil.Extensions
{
    public static class EnumHelper
    {
        /// <summary>获取枚举字段的注释</summary>
        /// <param name="value">枚举值</param>
        /// <returns>枚举字段的注释</returns>
        public static string GetDescription(this Enum value)
        {
            if (value == null)
            {
                return null;
            }

            var field = value.GetType().GetField(value.ToString(), BindingFlags.Static | BindingFlags.Public);
            if (field == null)
            {
                return null;
            }

            var customAttribute = field.GetCustomAttribute<DescriptionAttribute>(false);
            return string.IsNullOrEmpty(customAttribute?.Description)
                ? null
                : customAttribute.Description;
        }
    }
}
